<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="一级科室" prop="parentId">
        <el-select
            v-model="queryParams.parentId"
            placeholder="请选择一级科室"
            clearable
            filterable
            style="width: 200px"
            @change="handleQuery"
        >
          <el-option
              v-for="department in parentDepartmentOptions"
              :key="department.departmentId"
              :label="department.departmentName"
              :value="department.departmentId"
          />
        </el-select>
      </el-form-item>
      <!-- 新增状态筛选按钮组 -->
      <el-form-item label="状态" prop="status">
        <el-button-group>
          <el-button
              :type="queryParams.status === '1' ? 'primary' : ''"
              @click="handleStatusChange('1')"
              class="status-active-btn"
          >正常</el-button>
          <el-button
              :type="queryParams.status === '0' ? 'danger' : ''"
              @click="handleStatusChange('0')"
              class="status-inactive-btn"
          >停用</el-button>
        </el-button-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Plus"
            @click="handleAddParentAndSub"
            v-hasPermi="['department:departments:add']"
        >新增科室</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 分组显示二级科室 -->
    <div class="department-group-container" v-loading="loading">
      <div class="department-group" v-for="parentDept in departmentsGroupList" :key="parentDept.departmentId">
        <div class="parent-department">
          <div class="parent-info">
            <span class="parent-name">{{ parentDept.departmentName }}</span>
            <el-tag
                :type="parentDept.status === '1' ? 'success' : 'danger'"
                size="small"
                class="status-tag"
            >
              {{ parentDept.status === '1' ? '正常' : '停用' }}
            </el-tag>
          </div>
          <div class="parent-actions">
            <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleEditSubDepartments(parentDept)"
                v-hasPermi="['department:departments:edit']"
            >编辑二级科室</el-button>
            <el-button
                link
                :type="parentDept.status === '1' ? 'warning' : 'success'"
                :icon="parentDept.status === '1' ? 'Close' : 'Check'"
                @click="handleToggleParentStatus(parentDept)"
                v-hasPermi="['department:departments:edit']"
            >
              {{ parentDept.status === '1' ? '停用' : '启用' }}
            </el-button>
            <!-- 新增删除按钮 -->
            <el-button
                link
                type="danger"
                icon="Delete"
                @click="handleDeleteParentDept(parentDept)"
                v-hasPermi="['department:departments:remove']"
            >删除</el-button>
          </div>
        </div>
        <div class="sub-departments">
          <el-tag
              v-for="subDept in parentDept.childrenDepartments"
              :key="subDept.departmentId"
              class="sub-dept-tag"
              :type="subDept.status === '1' ? 'success' : 'info'"
              closable
              @close="handleDeleteSubDept(subDept)"
          >
            {{ subDept.departmentName }}
          </el-tag>
          <el-button
              type="primary"
              link
              icon="Plus"
              @click="handleAddSubDept(parentDept)"
              style="margin-left: 5px;"
          >添加</el-button>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="departmentsGroupList.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无科室数据" />
      </div>
    </div>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改二级科室对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="departmentsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="一级科室" prop="parentId">
          <el-select
              v-model="form.parentId"
              placeholder="请选择一级科室"
              style="width: 100%"
              :disabled="isEditingSubDepartments"
              filterable
              clearable
              @change="handleParentChange"
          >
            <el-option
                v-for="department in parentDepartmentOptions"
                :key="department.departmentId"
                :label="department.departmentName"
                :value="department.departmentId"
                :disabled="department.status === '0'"
            />
            <el-option
                v-if="showNewParentOption"
                key="new"
                label="+ 新建一级科室"
                value="new"
                class="new-parent-option"
            />
          </el-select>
        </el-form-item>

        <!-- 新建一级科室表单 -->
        <div v-if="showNewParentForm" class="new-parent-form">
          <el-divider content-position="left">新建一级科室</el-divider>
          <el-form-item label="一级科室" prop="newParentName">
            <el-input v-model="form.newParentName" placeholder="请输入一级科室名称" />
          </el-form-item>
          <el-form-item label="状态" prop="newParentStatus">
            <el-radio-group v-model="form.newParentStatus">
              <el-radio label="1" class="status-active">正常</el-radio>
              <el-radio label="0" class="status-inactive">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

        <el-form-item label="二级科室" prop="departmentName">
          <el-input v-model="form.departmentName" placeholder="请输入二级科室名称" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="1" class="status-active">正常</el-radio>
            <el-radio label="0" class="status-inactive">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量编辑二级科室对话框 -->
    <el-dialog title="编辑二级科室" v-model="openSubDeptEdit" width="600px" append-to-body>
      <div class="sub-dept-edit-container">
        <div class="current-parent">
          当前一级科室：{{ currentParentDept ? currentParentDept.departmentName : '' }}
          <el-tag
              :type="currentParentDept && currentParentDept.status === '1' ? 'success' : 'danger'"
              size="small"
              style="margin-left: 10px;"
          >
            {{ currentParentDept && currentParentDept.status === '1' ? '正常' : '停用' }}
          </el-tag>
        </div>
        <div class="sub-dept-list">
          <div class="sub-dept-item" v-for="(subDept, index) in currentSubDepartments" :key="index">
            <el-input v-model="subDept.departmentName" placeholder="科室名称" style="width: 200px; margin-right: 10px;" />
            <el-radio-group v-model="subDept.status" style="margin-right: 10px;">
              <el-radio label="1" class="status-active">正常</el-radio>
              <el-radio label="0" class="status-inactive">停用</el-radio>
            </el-radio-group>
            <el-button type="danger" icon="Delete" @click="removeSubDept(index)"></el-button>
          </div>
        </div>
        <div class="add-sub-dept">
          <el-button type="primary" icon="Plus" @click="addNewSubDept">添加二级科室</el-button>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveSubDepartments">保 存</el-button>
          <el-button @click="openSubDeptEdit = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Departments">
import { listDepartments, getDepartments, delDepartments, addDepartments, updateDepartments } from "@/api/department/departments"
import {listDoctor} from "@/api/medical/doctor.js";

const { proxy } = getCurrentInstance()
const { sys_normal_disable } = proxy.useDict('sys_normal_disable')

const departmentsList = ref([])
const departmentsGroupList = ref([]) // 分组后的科室列表
const open = ref(false)
const openSubDeptEdit = ref(false) // 批量编辑二级科室弹窗
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const title = ref("")
const parentDepartmentOptions = ref([]) // 一级科室下拉框选项
const isEditingSubDepartments = ref(false) // 是否正在编辑二级科室
const currentParentDept = ref(null) // 当前正在编辑的一级科室
const currentSubDepartments = ref([]) // 当前正在编辑的二级科室列表
const showNewParentOption = ref(true) // 显示新建一级科室选项
const showNewParentForm = ref(false) // 显示新建一级科室表单

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    parentId: null,
    status: null, // 新增状态筛选参数
    level: 1, // 查询一级科室用于分页
  },
  rules: {
    parentId: [
      { required: true, message: "一级科室不能为空", trigger: "blur" }
    ],
    departmentName: [
      { required: true, message: "科室名称不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "blur" }
    ],
    newParentName: [
      { required: true, message: "一级科室名称不能为空", trigger: "blur" }
    ],
    newParentStatus: [
      { required: true, message: "状态不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询科室管理列表 */
function getList() {
  loading.value = true

  // 先查询一级科室用于分页
  const parentParams = {
    ...queryParams.value,
    level: 1
  }

  listDepartments(parentParams).then(response => {
    const parentDepts = response.rows
    total.value = response.total

    // 然后查询所有二级科室
    const subDeptParams = {
      level: 2,
      pageNum: 1,
      pageSize: 1000 // 获取所有二级科室
    }

    listDepartments(subDeptParams).then(subResponse => {
      departmentsList.value = subResponse.rows

      // 如果有筛选条件，过滤一级科室
      let filteredParentDepts = parentDepts
      if (queryParams.value.parentId) {
        filteredParentDepts = parentDepts.filter(dept =>
            dept.departmentId === queryParams.value.parentId
        )
      }

      // 根据状态筛选
      if (queryParams.value.status) {
        filteredParentDepts = filteredParentDepts.filter(dept =>
            dept.status === queryParams.value.status
        )
      }

      // 分组处理科室数据
      departmentsGroupList.value = filteredParentDepts.map(parentDept => {
        const children = departmentsList.value.filter(dept =>
            dept.parentId === parentDept.departmentId
        )
        return {
          ...parentDept,
          childrenDepartments: children
        }
      })

      loading.value = false
    })
  })
}

/** 更新一级科室下拉框选项 */
function updateParentDepartmentOptions() {
  // 查询所有一级科室作为上级科室选项
  const params = {
    level: 1,
    pageNum: 1,
    pageSize: 1000 // 获取所有一级科室
  }
  listDepartments(params).then(response => {
    parentDepartmentOptions.value = response.rows
  })
}

/** 状态筛选按钮点击事件 */
function handleStatusChange(status) {
  if (queryParams.value.status === status) {
    // 如果点击已选中的状态，则取消筛选
    queryParams.value.status = null
  } else {
    queryParams.value.status = status
  }
  handleQuery()
}

/** 切换一级科室状态 */
function handleToggleParentStatus(parentDept) {
  const newStatus = parentDept.status === '1' ? '0' : '1'
  const statusText = newStatus === '1' ? '启用' : '停用'

  proxy.$modal.confirm(`确认要${statusText}一级科室"${parentDept.departmentName}"吗？`).then(() => {
    const updateData = {
      ...parentDept,
      status: newStatus
    }
    updateDepartments(updateData).then(() => {
      proxy.$modal.msgSuccess(`${statusText}成功`)
      getList()
    })
  }).catch(() => {})
}
/** 检查是否有医生绑定科室 */
function checkDoctorsBoundToDepartment(departmentId) {
  return new Promise((resolve) => {
    // 调用检查医生绑定的API
    // 这里需要根据实际API调整
    listDoctor({ departmentId: departmentId, pageSize: 1 }).then(response => {
      resolve(response.rows && response.rows.length > 0)
    }).catch(() => {
      resolve(false) // 如果API调用失败，默认允许删除
    })
  })
}

/** 删除一级科室 */
function handleDeleteParentDept(parentDept) {
  // 检查是否有关联的二级科室
  if (parentDept.childrenDepartments && parentDept.childrenDepartments.length > 0) {
    proxy.$modal.msgError(`无法删除一级科室"${parentDept.departmentName}"，请先删除其下的所有二级科室`)
    return
  }

  // 检查是否有医生绑定该科室
  checkDoctorsBoundToDepartment(parentDept.departmentId).then(hasDoctors => {
    if (hasDoctors) {
      proxy.$modal.msgError(`无法删除一级科室"${parentDept.departmentName}"，该科室下有关联的医生`)
      return
    }

    proxy.$modal.confirm(`是否确认删除一级科室"${parentDept.departmentName}"？`).then(function() {
      return delDepartments(parentDept.departmentId)
    }).then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
      updateParentDepartmentOptions()
    }).catch(() => {})
  })
}

/** 一级科室选择变化 */
function handleParentChange(value) {
  if (value === 'new') {
    showNewParentForm.value = true
    form.value.parentId = null
    // 清空二级科室名称，让用户重新输入
    form.value.departmentName = ''
  } else {
    showNewParentForm.value = false
  }
}

/** 新增一级科室及二级科室 */
function handleAddParentAndSub() {
  reset()
  open.value = true
  title.value = "新增一级科室及二级科室"
  isEditingSubDepartments.value = false
  showNewParentForm.value = true
  form.value.parentId = 'new'
  form.value.newParentStatus = '1'
  form.value.status = '1' // 默认二级科室状态为正常

  // 更新一级科室选项
  updateParentDepartmentOptions()
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
  showNewParentForm.value = false
}

// 表单重置
function reset() {
  form.value = {
    departmentId: null,
    departmentName: null,
    parentId: null,
    newParentName: null,
    newParentStatus: '1',
    level: 2, // 默认二级科室
    sortOrder: 0,
    description: null,
    status: "1", // 默认状态为正常
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("departmentsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  queryParams.value.parentId = null
  queryParams.value.status = null
  handleQuery()
}

/** 添加二级科室到指定一级科室 */
function handleAddSubDept(parentDept) {
  reset()
  form.value.parentId = parentDept.departmentId
  form.value.status = '1' // 默认状态为正常
  open.value = true
  title.value = "添加二级科室"
  isEditingSubDepartments.value = true
  showNewParentForm.value = false
}

/** 编辑二级科室（批量编辑） */
function handleEditSubDepartments(parentDept) {
  currentParentDept.value = parentDept

  // 先清空当前数据
  currentSubDepartments.value = []

  // 获取该一级科室下的所有二级科室
  const params = {
    parentId: parentDept.departmentId,
    level: 2,
    pageNum: 1,
    pageSize: 1000
  }

  loading.value = true
  listDepartments(params).then(response => {
    // 确保只显示当前一级科室的二级科室
    currentSubDepartments.value = response.rows
        .filter(dept => dept.parentId === parentDept.departmentId)
        .map(dept => ({
          departmentId: dept.departmentId,
          departmentName: dept.departmentName,
          parentId: dept.parentId,
          level: dept.level,
          sortOrder: dept.sortOrder,
          status: dept.status,
          description: dept.description
        }))

    openSubDeptEdit.value = true
    loading.value = false
  }).catch(error => {
    loading.value = false
    proxy.$modal.msgError("加载二级科室数据失败")
  })
}

/** 删除二级科室 */
function handleDeleteSubDept(subDept) {
  // 检查是否有医生绑定该科室
  checkDoctorsBoundToDepartment(subDept.departmentId).then(hasDoctors => {
    if (hasDoctors) {
      proxy.$modal.msgError(`无法删除二级科室"${subDept.departmentName}"，该科室下有关联的医生`)
      return
    }

    proxy.$modal.confirm('是否确认删除二级科室"' + subDept.departmentName + '"？').then(function() {
      return delDepartments(subDept.departmentId)
    }).then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    }).catch(() => {})
  })
}


/** 在批量编辑中移除二级科室 */
function removeSubDept(index) {
  const subDept = currentSubDepartments.value[index]
  if (subDept.departmentId) {
    // 如果是有ID的科室，需要确认删除
    proxy.$modal.confirm('是否确认删除二级科室"' + subDept.departmentName + '"？').then(function() {
      return delDepartments(subDept.departmentId)
    }).then(() => {
      currentSubDepartments.value.splice(index, 1)
      proxy.$modal.msgSuccess("删除成功")
    }).catch(() => {})
  } else {
    // 如果是新添加的科室，直接移除
    currentSubDepartments.value.splice(index, 1)
  }
}

/** 在批量编辑中添加新的二级科室 */
function addNewSubDept() {
  currentSubDepartments.value.push({
    departmentId: null,
    departmentName: '',
    parentId: currentParentDept.value.departmentId,
    level: 2,
    sortOrder: 0,
    status: '1', // 默认状态为正常
    description: ''
  })
}

/** 保存批量编辑的二级科室 */
function saveSubDepartments() {
  // 过滤出有效的二级科室（有名称的）
  const validSubDepts = currentSubDepartments.value.filter(dept => dept.departmentName && dept.departmentName.trim() !== '')

  if (validSubDepts.length === 0) {
    proxy.$modal.msgWarning("请至少填写一个有效的二级科室")
    return
  }

  // 验证所有新增的二级科室都设置了正确的 parentId
  validSubDepts.forEach(dept => {
    if (!dept.departmentId) {
      dept.parentId = currentParentDept.value.departmentId
    }
  })

  // 保存所有二级科室
  const savePromises = validSubDepts.map(dept => {
    if (dept.departmentId) {
      // 更新现有科室
      return updateDepartments(dept)
    } else {
      // 新增科室
      return addDepartments(dept)
    }
  })

  Promise.all(savePromises).then(() => {
    proxy.$modal.msgSuccess("保存成功")
    openSubDeptEdit.value = false
    getList()
  }).catch(error => {
    proxy.$modal.msgError("保存失败: " + error.message)
  })
}

/** 提交单个二级科室表单 */
function submitForm() {
  proxy.$refs["departmentsRef"].validate(valid => {
    if (valid) {
      if (showNewParentForm.value && form.value.parentId === 'new') {
        // 先创建一级科室
        const parentDeptData = {
          departmentName: form.value.newParentName,
          parentId: 0,
          level: 1,
          sortOrder: 0,
          status: form.value.newParentStatus,
          description: form.value.description
        }

        console.log('提交的一级科室数据:', parentDeptData)

        addDepartments(parentDeptData).then(parentResponse => {
          console.log('一级科室创建响应:', parentResponse)

          // 由于API不返回ID，我们需要通过查询来获取新创建的科室ID
          return new Promise((resolve, reject) => {
            // 延迟查询，确保数据已保存到数据库
            setTimeout(() => {
              const queryParams = {
                level: 1,
                pageNum: 1,
                pageSize: 50,
                departmentName: form.value.newParentName
              }

              listDepartments(queryParams).then(queryResponse => {
                if (queryResponse.rows && queryResponse.rows.length > 0) {
                  // 找到名称匹配的科室，取第一个（假设名称唯一）
                  const matchingDepts = queryResponse.rows.filter(
                      dept => dept.departmentName === form.value.newParentName
                  )

                  if (matchingDepts.length > 0) {
                    const newParentId = matchingDepts[0].departmentId
                    console.log('通过查询获取到科室ID:', newParentId)
                    resolve(newParentId)
                  } else {
                    reject(new Error('未找到新创建的科室'))
                  }
                } else {
                  reject(new Error('查询科室列表为空'))
                }
              }).catch(reject)
            }, 1000) // 延迟1秒确保数据保存
          })
        }).then(newParentId => {
          // 创建二级科室
          const subDeptData = {
            departmentName: form.value.departmentName,
            parentId: newParentId,
            level: 2,
            sortOrder: 0,
            status: form.value.status,
            description: form.value.description
          }

          console.log('提交的二级科室数据:', subDeptData)
          return addDepartments(subDeptData)
        }).then(() => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          reset()
          showNewParentForm.value = false
          getList()
          updateParentDepartmentOptions()
        }).catch(error => {
          console.error('创建科室失败:', error)
          proxy.$modal.msgError("新增失败: " + (error.message || '未知错误'))
        })
      } else {
        // 常规的二级科室新增/修改（原有代码保持不变）
        form.value.level = 2

        if (form.value.departmentId != null) {
          updateDepartments(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            reset()
            getList()
          })
        } else {
          addDepartments(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            reset()
            getList()
          })
        }
      }
    }
  })
}

// 初始化加载列表
getList()
// 初始化一级科室选项
updateParentDepartmentOptions()
</script>

<style scoped>
.department-group-container {
  min-height: 200px;
}

.department-group {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 16px;
  padding: 16px;
}

.parent-department {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.parent-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.parent-name {
  font-size: 16px;
  font-weight: bold;
  color: #409eff;
}

.parent-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-tag {
  margin-left: 8px;
}

.sub-departments {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.sub-dept-tag {
  margin: 4px;
}

.sub-dept-edit-container {
  padding: 10px;
}

.current-parent {
  margin-bottom: 15px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.sub-dept-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.add-sub-dept {
  margin-top: 15px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.new-parent-form {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 16px;
}

/* 状态按钮样式 */
.status-active-btn {
  color: #67c23a;
  border-color: #67c23a;
}

.status-active-btn:hover {
  background-color: #f0f9eb;
  border-color: #67c23a;
}

.status-inactive-btn {
  color: #f56c6c;
  border-color: #f56c6c;
}

.status-inactive-btn:hover {
  background-color: #fef0f0;
  border-color: #f56c6c;
}

/* 状态样式 */
.status-active {
  color: #67c23a;
}

.status-inactive {
  color: #909399;
}

:deep(.status-active .el-radio__label) {
  color: #67c23a;
}

:deep(.status-inactive .el-radio__label) {
  color: #909399;
}

:deep(.new-parent-option) {
  color: #409eff;
  font-weight: bold;
}
</style>